const moment = require("moment");
const Goods = require("../models/goods");
const GoodsConversion = require("../models/goodsConversion");
const scoreService = require("../services/scoreService");
const { Op } = require("sequelize");

//判断日期是否需要加0
function addZero(num) {
  return num < 10 ? "0" + num : num;
}

//获取某个用户某个商品的兑换记录
exports.getConversion = async function (userId, goodsId) {
  return await GoodsConversion.findAll({
    where: {
      userId,
      goodsId,
      [Op.or]: [{ useState: 1 }, { useState: 2 }],
    },
    limit: 1,
    order: [["createdAt", "DESC"]],
  });
};

//检查某个用户已兑换未使用商品是否过期
exports.check = async function (userId, todayDate) {
  const conversions = await GoodsConversion.findAll({
    where: {
      userId,
      useState: 1,
    },
    attributes: ["id", "createdAt", "useState"],
    include: {
      model: Goods,
      attributes: ["id", "useDay"],
      as: "goods",
    },
  });
  const length = conversions.length;
  if (length < 1) return;
  else {
    for (let i = 0; i < length; i++) {
      let date = new Date(conversions[i].createdAt);
      date =
        date.getFullYear() +
        "-" +
        addZero(date.getMonth() + 1) +
        "-" +
        addZero(date.getDate());
      date = new Date(date).getTime();
      if (
        todayDate - date >
        conversions[i].goods.useDay * 24 * 60 * 60 * 1000
      ) {
        conversions[i].useState = 0;
        await conversions[i].save();
      }
    }
    return;
  }
};

//添加兑换记录
exports.add = async function (userId, goodsId, score, useDay, title) {
  useDay = Number(useDay);
  score = Number(score);
  let endDate = new Date().getTime();
  endDate = endDate + useDay * 24 * 60 * 60 * 1000;
  endDate = moment(endDate).format("YYYY年MM月DD日");
  await GoodsConversion.create({
    userId,
    goodsId,
    score,
    endDate,
  });

  //添加积分消息
  await scoreService.add(userId, -score, `兑换${title}`);

  return;
};

//使用已兑换商品
exports.useGift = async function (userId, goodsId) {
  const useDate = moment().format("YYYY年MM月DD日");
  return GoodsConversion.update(
    { useState: 2, useDate },
    { where: { userId, goodsId, useState: 1 }, individualHooks: true }
  );
};

//获取商品好礼列表
exports.getList = async function (userId) {
  const unusedArr = await GoodsConversion.findAll({
    where: { userId, useState: 1 },
    include: {
      model: Goods,
      attributes: ["id", "img", "title", "merchant", "merchantImg"],
      as: "goods",
    },
    attributes: ["id", "useState", "endDate"],
    order: [["endDate", "ASC"]],
  });

  const usedArr = await GoodsConversion.findAll({
    where: { userId, useState: 2 },
    include: {
      model: Goods,
      attributes: ["id", "img", "title", "merchant", "merchantImg"],
      as: "goods",
    },
    attributes: ["id", "useState", "useDate"],
    order: [["useDate", "DESC"]],
  });

  const pastArr = await GoodsConversion.findAll({
    where: { userId, useState: 0 },
    include: {
      model: Goods,
      attributes: ["id", "img", "title", "merchant", "merchantImg"],
      as: "goods",
    },
    attributes: ["id", "useState", "endDate"],
    order: [["endDate", "ASC"]],
  });

  return {
    unusedArr,
    usedArr,
    pastArr,
  };
};
